package web.servlet;

import dao.DaoAlumnos;
import dao.impl.DaoAlumnosImpl;
import dto.Alumnos;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet(name = "ServletAlumnos", urlPatterns = {"/Alumnos"})
public class ServletAlumnos extends HttpServlet {

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        response.setContentType("text/html;charset=UTF-8");
        String accion = request.getParameter("accion");
        String result = null;
        String target = "index.jsp";

        DaoAlumnos daoAlumnos = new DaoAlumnosImpl();

        if (accion == null) {
            result = "Solicitud no recibida";

        } else if (accion.equals("QRY")) {
            List<Alumnos> list = daoAlumnos.alumnosQry();

            if (list != null) {
                request.setAttribute("list", list);
                target = "alumnosQry.jsp";
            } else {
                result = "Sin acceso a Base de Datos";
                target = "mensaje.jsp";
            }

        } else if (accion.equals("INS")) {
            Alumnos alumnos = new Alumnos();
            result = valida(request, alumnos);

            if (result == null) {
                result = daoAlumnos.alumnosIns(alumnos);
            }

            if (result != null) {
                request.setAttribute("alumno", alumnos);
                target = "alumnosIns.jsp";
            }

        } else if (accion.equals("DEL")) {
            String ids = request.getParameter("ids");

            String[] id = null;
            if ((ids == null) || (ids.trim().length() == 0)) {
                result = "No ha llegado idalumno(s)";
                target = "mensaje.jsp";
            } else {
                id = ids.split(",");
            }

            List<Integer> list = new LinkedList<Integer>();
            if (result == null) {
                for (String ix : id) {
                    try {
                        Integer idalumno = Integer.valueOf(ix);
                        list.add(idalumno);

                    } catch (NumberFormatException e) {
                        result = "Valor errado de idalumno";
                        target = "mensaje.jsp";
                        break;
                    }
                }
            }

            if (result == null) {
                result = daoAlumnos.alumnosDel(list);
            }

            if (result != null) {
                target = "mensaje.jsp";
            }

        } else if (accion.equals("GET")) {
            String id = request.getParameter("id");
            Integer idx = null;

            if (id != null) {
                try {
                    idx = Integer.valueOf(id);
                } catch (NumberFormatException e) {
                    result = "Valor errado de idalumno";
                    target = "mensaje.jsp";
                }
            } else {
                result = "ID alumno no recibido";
                target = "mensaje.jsp";
            }

            if (result == null) {
                Alumnos p = daoAlumnos.alumnosGet(idx);

                if (p != null) {
                    request.setAttribute("alumno", p);
                    target = "alumnosUpd.jsp";
                } else {
                    result = "ID alumno incorrecto";
                    target = "mensaje.jsp";
                }
            }

        } else if (accion.equals("UPD")) {
            Alumnos alumnos = new Alumnos();
            result = valida(request, alumnos);

            if (result == null) {
                result = daoAlumnos.alumnosUpd(alumnos);
            }

            if (result != null) {
                request.setAttribute("alumno", alumnos);
                target = "alumnosUpd.jsp";
            }

        } else {
            result = "Solicitud no reconocida";
        }

        if (result != null) {
            request.setAttribute("msg", result);
        }

        RequestDispatcher dispatcher
                = request.getRequestDispatcher(target);
        dispatcher.forward(request, response);
    }

    // <editor-fold defaultstate="collapsed" desc="apoyo">
    private String valida(HttpServletRequest request, Alumnos p) {
        String result = "<ul>";

        String idalumno = request.getParameter("idalumno");
        String alumno = request.getParameter("alumno");
        String nota1 = request.getParameter("nota1");
        String nota2 = request.getParameter("nota2");
        String nota3 = request.getParameter("nota3");
        String comentario = request.getParameter("comentario");

        Integer idalumnox = null;
        if (idalumno != null) {
            try {
                idalumnox = Integer.valueOf(idalumno);
            } catch (NumberFormatException e) {
                result += "<li>Valor errado de idalumno</li>";
            }
        }

        Integer nota1x = null;
        if (nota1 != null) {
            try {
                nota1x = Integer.valueOf(nota1);
            } catch (NumberFormatException e) {
                result += "<li>Valor errado de la Nota 1</li>";
            }
        }

        Integer nota2x = null;
        if (nota2 != null) {
            try {
                nota2x = Integer.valueOf(nota2);
            } catch (NumberFormatException e) {
                result += "<li>Valor errado de la Nota 2</li>";
            }
        }

        Integer nota3x = null;
        if (nota3 != null) {
            try {
                nota3x = Integer.valueOf(nota3);
            } catch (NumberFormatException e) {
                result += "<li>Valor errado de la Nota 3</li>";
            }
        }

        if ((alumno == null) || (alumno.trim().length() == 0)) {
            result += "<li>Ingrese Nombre del Alumno</li>";
        }

        if ((nota1 == null) || (nota1.trim().length() == 0)) {
            result += "<li>ingrese nota 1 del alumno<br/>";
        }

        if ((nota2 == null) || (nota2.trim().length() == 0)) {
            result += "<li>ingrese nota 2 del alumno<br/>";
        }

        if ((nota3 == null) || (nota3.trim().length() == 0)) {
            result += "<li>ingrese nota 3 del alumno<br/>";
        }

        if ((comentario == null) || (comentario.trim().length() == 0)) {
            result += "<li>Ingrese comentario<br/>";
        }

        /*
         Double preciox = null;
         if ((precio == null) || (precio.trim().length() == 0)) {
         result += "<li>Ingrese Precio de Producto</li>";
         } else {
         try {
         preciox = Double.valueOf(precio);
         } catch (NumberFormatException e) {
         result += "<li>Precio de Producto incorrecto</li>";
         }
         }
         */
        p.setIdalumno(idalumnox);
        p.setAlumno(alumno);
        p.setNota1(nota1x);
        p.setNota2(nota2x);
        p.setNota3(nota3x);
        p.setComentario(comentario);

        if (result.equals("<ul>")) {
            result = null;
        } else {
            result += "</ul>";
        }

        return result;
    }// </editor-fold>

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
